from celery import Celery
from app.extensions import db
from app.models.orders import Orders
import pickle
import requests
import json

def make_celery(app_name=__name__):
    return Celery('mytask', backend='redis://localhost:6379/1', broker='redis://localhost:6379/2')

# 创建celery的工厂函数
def init_celery(app):
    celery = Celery(
        'mytask',
        backend=app.config['CELERY_RESULT_BACKEND'],
        broker=app.config['CELERY_BROKER_URL']
    )
    class ContextTask(celery.Task):
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return self.run(*args, **kwargs)
    celery.Task = ContextTask
    return celery

celery = make_celery()

@celery.task
def pull(user_id):
    # csrf_token = flask_redis.hmget(user_id, 'csrf_token')[0].decode('utf-8')
    # exportkey = flask_redis.hmget(user_id, 'exportkey')[0].decode('utf-8')
    # cookies = dict(pickle.loads(flask_redis.hmget(user_id, 'cookies')[0]))
    csrf_token = ''
    exportkey = ''
    cookies = ''
    url = 'https://wx.tenpay.com/userroll/userrolllist?classify_type=3&count=20&csrf_token={}&exportkey={}&sort_type=1'.format(csrf_token, exportkey)
    res = requests.get(url, cookies=cookies)
    return json.loads(res.text)['record']

